<style lang="less" scoped>
.ipt-sty {
  width: 98%;
  border: 1px solid #ccc;
  border-radius: 4px;
  height: 150px;
  text-align: center;
  font-size: 20px;
}
</style>

<template>
  <div class="contain drawall">
    <app-head :show="showstate"
              :title="pagetitle"></app-head>
    <div class="ft14">
      <tab bar-active-color="#23a5a5"
           defaultColor="#333333"
           active-color="#23a5a5"
           :line-width='2'
           v-model="tabNo">
        <tab-item @on-item-click="tabNo = 0">整车提货</tab-item>
        <!-- <tab-item @on-item-click="tabNo = 1">区域提货</tab-item> -->
      </tab>
    </div>

    <div>
      <div class="car-bbinfo-card">
        <div class="bbno lineb">排车单号：{{data.ATVNo}}</div>
      </div>

      <div class="car-bbinfo-card"
           style="position:relative"
           v-if='tabNo === 1'>
        <div class="bbmain lineb">
          <popup-picker style="z-index:1; background:transparent"
                        :title="AreaPickerTitle"
                        :data="AreaList"
                        v-model="selectedArea"
                        @on-change="getText"
                        :placeholder="'请选择'"
                        :show-name="true"></popup-picker>
          <div style="position:absolute; top:0.2rem; right:0.45rem; font-size:16px; z-index:0; color:#888">{{selectedTextArea}}</div>
        </div>
      </div>

      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <p class="displayflex"><i>配送路线</i><label class="flex1">{{data.routeName}}</label></p>
          <p class="displayflex"><i>承运商</i><label class="flex1">{{data.deliverName}}</label></p>
          <p class="displayflex"><i>车牌号</i><label class="flex1">{{data.PlateNumber}}</label></p>
          <p class="displayflex"><i>派单司机</i><label class="flex1">{{data.driver1Name}}</label></p>
          <p class="displayflex"><i>订单数</i><label class="flex1">{{datas.length}}</label></p>
          <!-- <p class="displayflex"><i>总件数</i><label class="flex1">{{data.totalPkgs}} 整箱+拼箱+袋</label></p> -->
        </div>
      </div>

      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <div class="ipt flex1">
            <input type="text"
                   class="ipt-sty"
                   placeholder="输入提货泊位"
                   v-model="Berth">
          </div>
        </div>
      </div>

      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <p class="displayflex"><i>取货地址数</i><label class="flex1">{{data.depAddressList.length}}</label></p>
          <p class="displayflex"><i>送货地址数</i><label class="flex1">{{data.arrivalAddressCount}}</label></p>
          <p class="displayflex"><i>客户数</i><label class="flex1">{{data.cutomerCount}}</label></p>
        </div>
      </div>

      <template v-if="tabNo === 0">
        <div data
             class="car-bbinfo-card">
          <div data
               class="bbmain lineb ">
            <div data
                 class="vux-cell-box"
                 v-on:click="showDepAddress=true">
              <div class="weui-cell vux-tap-active weui-cell_access">
                <div class="weui-cell__hd">
                  <label class="weui-label"
                         style="display: block; width: auto;">共计{{data.depAddressList.length}}个取货地址</label>
                </div>
                <div class="vux-cell-primary vux-popup-picker-select-box">
                  <div class="vux-popup-picker-select"
                       style="text-align: right;">
                    <span class="vux-popup-picker-placeholder vux-cell-placeholder">查看</span>
                  </div>
                </div>
                <div class="weui-cell__ft"></div>
              </div>
            </div>
          </div>
        </div>
        <div data
             class="car-bbinfo-card mb30">
          <div data
               class="bbmain lineb ">
            <div data
                 class="vux-cell-box"
                 v-on:click="showArrAddress=true">
              <div class="weui-cell vux-tap-active weui-cell_access">
                <div class="weui-cell__hd">
                  <label class="weui-label"
                         style="display: block; width: auto;">共计{{data.arrAddressList.length}}个送货地址</label>
                </div>
                <div class="vux-cell-primary vux-popup-picker-select-box">
                  <div class="vux-popup-picker-select"
                       style="text-align: right;">
                    <span class="vux-popup-picker-placeholder vux-cell-placeholder">查看</span>
                  </div>
                </div>
                <div class="weui-cell__ft"></div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- <div class="car-bbinfo-card">
        <div class="bbmain lineb">
          <datetime class="vux-form" :format="'YYYY-MM-DD HH:mm'" v-model="leaveDate" :show.sync="visibility" :start-date="pickerStartDate" :end-date="pickerEndDate" title="实际驶离时间" placeholder="点击选择"></datetime>
        </div>
      </div>
      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <x-textarea v-model="Memo" :placeholder="'备注'" :max="200" autosize style="color:#888; font-size:16px;"></x-textarea>
        </div>
      </div> -->

      <div class="displayflex form-btn"
           v-if="tabNo === 0">
        <div class="flex1"
             v-on:click="drawAll()">确定提货</div>
        <!-- <div class="flex1 cancel" v-on:click="cancelOrder()">取消订单</div> -->
      </div>

      <div class="displayflex form-btn"
           v-if="tabNo === 1">
        <div class="flex1"
             v-on:click="drawRegion()">确定提货</div>
      </div>

      <actionsheet v-model="showDepAddress"
                   :menus="data.depAddressList"
                   show-cancel
                   :cancel-text="'关闭'">
        <p slot="header"
           v-html="tipD"></p>
      </actionsheet>
      <actionsheet v-model="showArrAddress"
                   :menus="data.arrAddressList"
                   show-cancel
                   :cancel-text="'关闭'">
        <!-- :menus="data.arrAddressList" -->
        <p slot="header"
           v-html="tipA"></p>
      </actionsheet>
    </div>
  </div>
</template>

<script>
import appHead from '@/components/core/header/app_headbar.vue';
import tools from '../../tools/tool.js';
import { mapState } from "vuex";

export default {
  components: {
    appHead,
  },
  data () {
    return {
      data: {
        actionsList: [],
        ATVNo: '',
        Guid: '',
        routeName: '',
        deliverName: '',
        driver1Name: '',
        totalPkgs: 0,
        arrivalAddressCount: 0,
        cutomerCount: 0,
        depAddressList: [],
        arrAddressList: [],
      },
      datas: {},
      Memo: '',

      tabNo: 0,
      showDepAddress: false,
      showArrAddress: false,
      visibility: false,
      leaveDate: '',
      pickerStartDate: '',
      pickerEndDate: '',
      filter: this.$options.filters,
      AreaList: [],
      selectedArea: [],
      selectedTextArea: '',
      Berth: '',
    }
  },
  watch: {
    selectedArea: {
      handler (n, o) {
        if (n.toString() !== o.toString()) {
          this.getData();
        }
      },
      deep: true
    },
    tabNo (n, o) {
      if (n === 0) {
        this.AreaList = [];
        this.selectedArea = [];
        this.selectedTextArea = '';
        this.getData();
      } else {
        this.selectedArea.splice(0, 1, this.AreaList[0][0].value);
        this.getData();
      }
    }
  },
  computed: {
    AreaPickerTitle () {
      return `共计${this.AreaList[0].length}个取货地`;
    },
    tipD () {
      return `起始地<br><span class="actitle">共计${this.data.depAddressList.length}个地址</span>`;
    },
    tipA () {
      return `目的地<br><span class="actitle">共计${this.data.arrAddressList.length}个地址</span><br>`;
    },
    ...mapState({
      pagetitle: state => state.cfg.appBarTitle,
      showstate: state => state.cfg.showAppBar,
    }),
    userinfo () {
      return localStorage.userinfo ? JSON.parse(localStorage.userinfo) : null
    }
  },
  created () {
    this.leaveDate = tools.getNow(new Date(), 'Min', 30, 'YMDHM');
    this.pickerStartDate = tools.getNow(new Date(), 'Year', -3, 'YMD');
    this.pickerEndDate = tools.getNow(new Date(), 'Year', 3, 'YMD');
    this.getData();
  },
  mounted () {

  },
  methods: {
    getData () {
      let query = {
        Guid: this.$route.query.Guid,
        LogState: 51,
        PageIndex: 1,
        PageSize: 99999,
      }
      if (this.selectedArea.length > 0) {
        let arg = JSON.parse(JSON.stringify(this.selectedArea))[0];
        if (typeof (arg) === 'string') {
          arg = arg.split(',');
        }
        query.DepartureProvince = arg[0];
        query.DepartureCity = arg[1];
      }
      this.Ajax.post("SearchPickUpOrders", query).then(resp => {
        if (resp.IsSuccess) {
          this.datas = resp.Datas;
          console.log(resp.Datas);
          let depAddr = [],
            arrAddr = [],
            totalPkgs = 0,
            inx = 0,
            customer = [];


          resp.Datas.forEach((x, index) => {
            this.Berth = x.Berth;
            // let depCode = `${x.DepartureProvince}${x.DepartureCity}`,
            //     depText = `${this.filter.province(x.DepartureProvince)}${this.filter.city(x.DepartureCity)}`,
            //     depCodeArr = [x.DepartureProvince, x.DepartureCity],
            //     arrCode = `${x.ArrivalProvince}${x.ArrivalCity}`,
            //     arrText = `${this.filter.province(x.ArrivalProvince)}${this.filter.city(x.ArrivalCity)}`,
            //     arrCodeArr = [x.ArrivalProvince, x.ArrivalCity],
            //     depItem = {
            //       name: depText,
            //       label: depText,
            //       value: depCodeArr,
            //       code: depCode,
            //     };
            //     let arrItem = {
            //       name: arrText,
            //       label:arrText,
            //       value: arrCodeArr,
            //       code: arrCode,
            //     };
            totalPkgs += x.Pkgs;
            if (customer.indexOf(x.SendContacts) == -1) {
              customer.push(x.SendContacts);
            }
            if (depAddr.indexOf(x.DepartureAddress) == -1) {
              depAddr.push(x.DepartureAddress);
            }
            if (arrAddr.indexOf(x.ArrivalAddress) == -1) {
              arrAddr.push(x.ArrivalAddress);
            }
            //depAddr.push(x.DepartureAddress);
            //arrAddr.push(x.ArrivalAddress);
            // depAddr.push(depItem);
            // arrAddr.push(arrItem);
          })

          // depAddr = this.mapReduce(depAddr, 'code');
          // arrAddr = this.mapReduce(arrAddr, 'code');
          // customer = [...new Set(customer)];
          // if(this.AreaList.length === 0){
          //   this.AreaList.push(depAddr);
          // }


          this.data.ATVNo = resp.Datas[0].ATVNo,
            this.data.Guid = resp.Datas[0].Guid,
            this.data.routeName = resp.Datas[0].RouteName,
            this.data.deliverName = resp.Datas[0].DeliverName,
            this.data.driver1Name = resp.Datas[0].Driver1Name,
            this.data.PlateNumber = resp.Datas[0].PlateNumber,
            this.data.totalPkgs = totalPkgs,
            this.data.arrivalAddressCount = arrAddr.length,
            this.data.cutomerCount = customer.length;
          this.data.depAddressList = depAddr;
          this.data.arrAddressList = arrAddr;
          for (let i = 0; i < this.data.arrAddressList.length; i++) {
            inx++;
            this.data.arrAddressList[i].label = inx + ' ' + this.data.arrAddressList[i].label;
          }
          console.log(this.data.arrAddressList);
        } else {
          this.Toast({
            message: "列表为空，请稍后刷新"
          });
        }
      });
    },

    drawAll () {
      let query = {
        Guid: this.data.Guid,
        ActualDepartureDate: this.leaveDate,
        Memo: this.Memo,
        PRContactsTel: this.userinfo.MobileTel1,
        Berth: this.Berth
      };
      this.Ajax.post("DriverDrawAllOrder", query).then(resp => {
        if (resp.IsSuccess) {
          this.Toast({
            message: "操作成功",
          });
          this.$router.go(-1);
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    drawRegion () {
      let query = {
        AtvehicleDetail: this.datas,
        Guid: this.data.Guid,
        ActualDepartureDate: this.leaveDate,
        Memo: this.Memo,
        PRContactsTel: this.userinfo.MobileTel1
      }
      this.Ajax.post("DriverDrawAllOrderByRegion", query).then(resp => {
        if (resp.IsSuccess) {
          this.Toast({
            message: "操作成功",
          });
          this.$router.go(-1);
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    cancelOrder () {
      let _this = this;
      this.$vux.confirm.show({
        content: '确认取消订单？',
        onCancel () {
          return false;
        },
        onConfirm () {
          let query = {
            ATVGuid: _this.$route.query.Guid,
            TenantGuid: _this.userinfo.TenantGuid,
          }
          _this.Ajax.post("RefusalOrder", query).then(resp => {
            if (resp.IsSuccess) {
              _this.Toast({
                message: "提货已取消",
                duration: 1000,
              });
              setTimeout(() => { _this.$router.push({ path: '/driver/carDraw' }) }, 1000)
            } else {
              _this.Toast({
                message: resp.ErrorMessage
              });
            }
          });
        }
      })
    },

    getText (e) {
      let arg = e[0];
      if (typeof (arg) === 'string') {
        arg = e[0].split(',');
      }
      this.selectedTextArea = `${this.filter.province(arg[0])}${this.filter.city(arg[1])}`;
    },

    mapReduce (arr, keyName) {
      let obj = {};
      arr = arr.reduce((item, next) => {
        obj[next[keyName]] ? '' : obj[next[keyName]] = true && item.push(next);
        return item;
      }, []);
      return arr;
    }
  }
}
</script>
